<template>
    <div>
      <h1>promise vs observable</h1>
      <h2>see the console</h2>
      <div style="color:#fff;background-color: #000;height: 50vh;width: 50vw;white-space: pre-line">
        {{log}}
      </div>
    </div>
</template>

<script>
  import * as rx from "rxjs";
  /// 演示 promise observable区别
  export default {
    name: "base-01",
    data(){
      return {log:''}
    },
    methods:{
      printLog(xs){
        xs.forEach(s => this.log = this.log + '\n' + JSON.stringify(s))
      }
    },
    created(){
      console.clear();
      let self = this
      //old 方式,仅做兼容,不再提供类型
      //推荐方式
      let source6 = new rx.Observable(subscriber => {
        console.log('订阅者->','a','b', subscriber, subscriber.closed)
        //throw 'my bad err init'; //将在错误订阅中捕获
        const to = setTimeout(function () {
          console.log('timeout hit',self.printLog) //超时
          try {
            if (!window.s) throw 'my bad err'; //如果订阅者不捕获(try catch),那么抛到顶层!!!
            subscriber.next(42);
            subscriber.complete()
          } catch (err) {
            subscriber.error(err) //显式调用,
          }
        }, 1000);
        console.log('start....')
        return function () { //解构回调
          console.log('返回解构回调,清理资源....')
          clearTimeout(to)
        }
      });

      const sub = source6.subscribe(
        function (x) {
          console.log(`next ${x}`)
        },
        function (err) {
          console.error('caught',err)
        },
        function () {
          console.info('完成!')
        }
      );
      // setTimeout(() => {
      //   console.log('取消订阅...');
      //   sub.unsubscribe()
      // },500);
    }
  }
</script>

<style scoped>

</style>
